﻿using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace MaskDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
           
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //new Window1().MaskShowDialog();
            ShowModel(this);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

        }

        private  AdornerLayer GetAdornerLayer(Visual visual)
        {
            var decorator = visual as AdornerDecorator;
            if (decorator != null)
                return decorator.AdornerLayer;
            var presenter = visual as ScrollContentPresenter;
            if (presenter != null)
                return presenter.AdornerLayer;
            var visualContent = (visual as Window)?.Content as Visual;
            return AdornerLayer.GetAdornerLayer(visualContent ?? visual);
        }

        private Adorner adorner;
        private AdornerLayer adornerLayer;
        public void ShowModel(Visual visual)
        {

            Window window = null;
            if (Application.Current.Windows.Count > 0)
            {
                window = Application.Current.Windows.OfType<Window>().FirstOrDefault(o => o.IsActive);
                if (window == null)
                    window = Enumerable.FirstOrDefault(Application.Current.Windows.OfType<Window>());
            }
            var _layer = ControlsHelper.GetAdornerLayer(window);
            if (_layer == null) return;

            adorner = new SimpleAdorner(_layer)
            {
                Child = new Border()
                {
                    Background = new SolidColorBrush(Colors.Black),
                    Opacity=0.7
                }
            };
            _layer.Add(adorner);
            Window1 window1 = new Window1();
            window1.Owner = window;
            window1.Closed += delegate {
                _layer.Remove(adorner);
            };
            var result=  window1.ShowDialog();
        }



        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            adornerLayer.Remove(adorner);
        }
    }
}
